# -*- coding: utf-8 -*-
from match import Extractor
import os.path
import regex as re
from storage.digit_util import *

# 抽取所有罪名的共同犯罪、数罪并罚（聚法案例上没有标记了数罪并罚的文书）
# 走私、贩卖、运输、制造毒品罪 辩护要点里的要素
# 抢劫罪 辩护要点里的要素（缺少数据，待补充之后选定）
# 故意伤害罪 辩护要点里的要素（缺少数据，待补充之后选定）

class GongTongExtractor(Extractor):

    # 共同犯罪适用于所有罪名，所以直接返回True
    @staticmethod
    def is_my_job(file_path):
        return True

    @staticmethod
    def extract(text):
        result = {}
        have_hui_zui = re.search(r"(共同(实施|故意)?犯罪)", text) is not None
        result["共同犯罪"] = int(have_hui_zui)
        if result["共同犯罪"] == 0:
            result["共同犯罪"] += 2
        return result


class ShuZuiExtractor(Extractor):

    # 数罪并罚适用于所有罪名，所以直接返回True
    # 聚法案例上没有标记了数罪并罚的文书
    @staticmethod
    def is_my_job(file_path):
        return True

    @staticmethod
    def extract(text):
        result = {}
        have_hui_zui = re.search(r"数罪并罚", text) is not None
        result["shuzuibingfa"] = int(have_hui_zui)
        if result["shuzuibingfa"] == 0:
            result["shuzuibingfa"] += 2
        return result


class DuPinBianHuExtractor(Extractor):
    """
    目前毒品罪要素抽取召回率：
    '冰毒（甲基苯丙胺、麻古）': 69.60%
    '贩卖毒品': 53.88%
    '吸食毒品': 46.61%
    '走私、运输': 30.00%
    '购买毒品': 28.34%
    '海洛因': 22.085
    'K粉（氯胺酮）': 10.07%
    '大麻': 3.5%
    '人赃俱获': 1.4%
    """
    @staticmethod
    def is_my_job(file_path):
        if os.path.basename(file_path) == '非法持有毒品罪.json':
            return True
        else:
            return False 

    @staticmethod
    def extract(text):
        result = {}
        du_pin_zui = list(set(re.findall("甲基苯丙胺|冰毒|麻古|麻果|海洛因|贩卖毒品|吸食|氯胺酮|购毒|购买毒品|贩毒|贩卖毒品|大麻|人赃俱获|走私|运输|运送|送到", text)))
        result["bianhuyaodian"] = du_pin_zui
        return result

class PangJueJieGuo(Extractor):
    # 不是抽取划分里的, 我用来做测试的。
    @staticmethod
    def is_my_job(file_path):
        return True


    @staticmethod
    def extract(text):
        result = {}
        pan_jue_jie_guo = list(set(["\n".join(re.findall(r"有期徒刑[\u4e00-\u9fa5]{1,4}年", text))
            , "\n".join(re.findall(r"无期徒刑", text)) , "\n".join(re.findall(r"死刑", text))\
              , "\n".join(re.findall(r"剥夺政治权利终身", text)), "\n".join(re.findall(r"缓刑[\u4e00-\u9fa5]{1,4}年", text))\
            , '\n'.join(re.findall(r"罚金.{1,6}元", text)) + "\n".join(re.findall(r"剥夺政治权利[\u4e00-\u9fa5]{1,4}年", text))\
            , '\n'.join(re.findall(r"有期徒刑[\u4e00-\u9fa5]{1,3}个月", text))]))
        result['panjuejieguo'] = " ".join(pan_jue_jie_guo)
        return result


class QiangJieBianHuExtractor(Extractor):
    @staticmethod
    def is_my_job(file_path):
        if os.path.basename(file_path) == '抢劫罪.json':
            return True
        else:
            return False

    @staticmethod
    def extract(text):
        result = {}
        qiang_jie_zui = list(set(re.findall("数额较大|退赃|态度端正|谅解|销赃|多次抢夺", text)))
        result["bianhuyaodian"] = qiang_jie_zui
        return result

class GuYiShanHaiBianHuExtractor(Extractor):
    @staticmethod
    def is_my_job(file_path):
        return "伤害" in file_path

    @staticmethod
    def extract(text):
        result = {}
        gu_yi_shan_hai_zui = list(set(re.findall("殴打|持刀|菜刀|水果刀|西瓜刀|轻微伤|故意|骨折|打伤|休克|致死|杀人|精神病", text)))
        result["bianhuyaodian"] = gu_yi_shan_hai_zui
        return result

class TuiZangExtractor(Extractor):

    @staticmethod
    def is_my_job(file_path):
        return True

    @staticmethod
    def extract(text):
        result = {}
        have_hui_zui = re.search(r"积极退赃", text) is not None
        result["jijituizang"] = int(have_hui_zui)
        if result["jijituizang"] == 0:
            result["jijituizang"] += 2
        return result

class ZhuDongPeiChangExtractor(Extractor):

    @staticmethod
    def is_my_job(file_path):
        return True

    @staticmethod
    def extract(text):
        result = {}
        have_hui_zui = re.search(r"主动赔偿", text) is not None
        result["zhudongpeichang"] = int(have_hui_zui)
        if result["zhudongpeichang"] == 0:
            result["zhudongpeichang"] += 2
        return result



class RenZuiExtractor(Extractor):

    @staticmethod
    def is_my_job(file_path):
        return True

    @staticmethod
    def extract(text):
        result = {}
        have_hui_zui = re.search(r"认罪态度较好|认罪认罚", text) is not None
        result["renzuirenfa"] = int(have_hui_zui)
        if result["renzuirenfa"] == 0:
            result["renzuirenfa"] += 2
        return result

class CangYuExtractor(Extractor):

    @staticmethod
    def is_my_job(file_path):
        return True

    @staticmethod
    def extract(text):
        result = {}
        have_hui_zui = re.search(r"积极参与", text) is not None
        result["jijicangyu"] = int(have_hui_zui)
        if result["jijicangyu"] == 0:
            result["jijicangyu"] += 2
        return result




class QiaoZhaBianHuExtractor(Extractor):
    @staticmethod
    def is_my_job(file_path):
        return "敲诈" in file_path

    @staticmethod
    def extract(text):
        result = {}
        Regx = re.compile("(([1-9]\\d*[\\d,，]*\\.?\\d*)|(0\\.[0-9]+))(元|百万|万元|亿元|万|亿)")
        temp_result_set = [term for term in re.split(r'[""“”;,!:：；，。！]', text) if '元' in term]
        is_digit = re.compile('-?\d+\.?\d*e?-?\d*?')
        result_set = [_ for _ in temp_result_set if is_digit.findall(_)]
        money_result = [Regx.search(term).group() for term in result_set if Regx.search(term) is not None]
        if money_result is not None:
            result["涉及金额"] = str(get_max_money(money_result)) + "元"
        result["危害公共安全、严重危害人身权利"] = re.search(r"放火|爆炸|危害公共安全|杀人|绑架", text) is not None
        result["黑社会性质"] = re.search(r"黑社会|黑恶", text) is not None
        result["冒充身份"] = re.search(r"国家机关|军人|冒充|假扮|伪造身份", text) is not None
        result["被害人谅解"] = re.search(r"谅解|原谅", text) is not None
        result["敲诈亲人"] = re.search(r"亲属|亲人|近亲", text) is not None
        return result

class QiaoZhaExtractor(Extractor):
    @staticmethod
    def is_my_job(file_path):
        return "敲诈" in file_path

    @staticmethod
    def extract(text):
        result = {}
        Regx = re.compile("(([1-9]\\d*[\\d,，]*\\.?\\d*)|(0\\.[0-9]+))(元|百万|万元|亿元|万|亿)")
        temp_result_set = [term for term in re.split(r'[""“”;,!:：；，。！]', text) if '元' in term]
        is_digit = re.compile('-?\d+\.?\d*e?-?\d*?')
        result_set = [_ for _ in temp_result_set if is_digit.findall(_)]
        money_result = [Regx.search(term).group() for term in result_set if Regx.search(term) is not None]
        if money_result is not None:
            if get_max_money(money_result) == None:
                result["涉及金额"] = float(0.0)
            else:
                result["涉及金额"] = float(get_max_money(money_result))
        result["危害公共安全、严重危害人身权利"] = re.search(r"放火|爆炸|危害公共安全|杀人|绑架", text) is not None
        result["黑社会性质"] = re.search(r"黑社会|黑恶", text) is not None
        result["冒充身份"] = re.search(r"国家机关|军人|冒充|假扮|伪造身份", text) is not None
        result["被害人谅解"] = re.search(r"谅解|原谅", text) is not None
        result["敲诈亲人"] = re.search(r"亲属|亲人|近亲", text) is not None
        return result

class DaoQieExtractor(Extractor):
    @staticmethod
    def is_my_job(file_path):
        return "盗窃" in file_path

    @staticmethod
    def extract(text):
        result = {}
        Regx = re.compile("(([1-9]\\d*[\\d,，]*\\.?\\d*)|(0\\.[0-9]+))(元|百万|万元|亿元|万|亿)")
        temp_result_set = [term for term in re.split(r'[""“”;,!:：；，。！]', text) if '元' in term]
        is_digit = re.compile('-?\d+\.?\d*e?-?\d*?')
        result_set = [_ for _ in temp_result_set if is_digit.findall(_)]
        money_result = [Regx.search(term).group() for term in result_set if Regx.search(term) is not None]
        if money_result is not None:
            if get_max_money(money_result) == None:
                result["涉及金额"] = float(0.0)
            else:
                result["涉及金额"] = float(get_max_money(money_result))
        result["入户盗窃"] = re.search(r"入户", text) is not None
        result["携带凶器"] = re.search(r"凶器", text) is not None
        result["扒窃"] = re.search(r"扒窃|扒手", text) is not None
        result["盗窃金融机构"] = re.search(r"金融机构|银行", text) is not None
        result["盗窃文物"] = re.search(r"文物", text) is not None
        return result

class WeiFanJTFGExtractor(Extractor):
    @staticmethod
    def is_my_job(file_path):
        return "交通" or "驾驶" in file_path

    @staticmethod
    def extract(text):
        result = {}
        zhongshan = re.search(r"重伤", text) is not None
        result["zhongshan"] = int(zhongshan)
        siwang = re.search(r"死亡|致死", text) is not None
        result["siwang"] = int(siwang)
        taoyi = re.search(r"逃逸", text) is not None
        result["taoyi"] = int(taoyi)
        zuijiu = re.search(r"醉酒", text) is not None
        result["zuijiu"] = int(zuijiu)
        for i in result.keys():
            if result[i] == 0:
                result[i] += 2
        return result

class ZuoAnGongJuExtractor(Extractor):
    @staticmethod
    def is_my_job(file_path):
        return "伤害" in file_path

    @staticmethod
    def extract(text):
        result = {}
        chidao = re.search(r"刀", text) is not None
        result["chidao"] = int(chidao)
        gunbang = re.search(r"棍|棒", text) is not None
        result["gunbang"] = int(gunbang)
        tushou = re.search(r"拳|徒手", text) is not None
        result["tushou"] = int(tushou)
        chiqiang = re.search(r"枪", text) is not None
        result["chiqiang"] = int(chiqiang)
        zhengdangfangwei = re.search(r"正当防卫", text) is not None
        result["zhengdangfangwei"] = int(zhengdangfangwei)
        for i in result.keys():
            if result[i] == 0:
                result[i] += 2
        return result


class ZuoAnDuiXiangExtractor(Extractor):
    @staticmethod
    def is_my_job(file_path):
        return "盗窃" in file_path

    @staticmethod
    def extract(text):
        result = {}
        jinrongjigong = re.search(r"金融|银行", text) is not None
        result["jinrongjigong"] = int(jinrongjigong)
        wenwu = re.search(r"文物", text) is not None
        result["wenwu"] = int(wenwu)
        xinyongka = re.search(r"信用卡", text) is not None
        result["xinyongka"] = int(xinyongka)
        fapiao = re.search(r"发票", text) is not None
        result["fapiao"] = int(fapiao)
        dianlimeiqitianranqi = re.search(r"电力|煤气|天然气", text) is not None
        result["dianlimeiqitianranqi"] = int(dianlimeiqitianranqi)
        weijinping = re.search(r"违禁品", text) is not None
        result["weijinping"] = int(weijinping)
        gerencaiwu = re.search(r"个人财物", text) is not None
        result["gerencaiwu"] = int(gerencaiwu)
        for i in result.keys():
            if result[i] == 0:
                result[i] += 2
        return result


if __name__ == '__main__':
    print(QiaoZhaExtractor.extract("冒充他人敲诈亲人，但获得了家属谅解。"))
    print(DaoQieExtractor.extract("入户盗窃"))
    from match import *
    from storage import *
    import json
    import os

    # data_util = DataUtil("../data/敲诈勒索罪")
    data_util = DataUtil("../data/盗窃罪")

    # extractors = [QiaoZhaExtractor]
    extractors = [DaoQieExtractor]

    file_path, text = data_util.next_line()
    count_dict = {}
    # count_key_list = ["涉及金额", "危害公共安全、严重危害人身权利", "黑社会性质", "冒充身份", "被害人谅解", "敲诈亲人"]

    count_key_list = ["涉及金额", "入户盗窃", "携带凶器", "扒窃", "盗窃金融机构", "盗窃文物"]

    while text:
        text_json = json.loads(text)
        if file_path not in count_dict:
            count_dict[file_path] = {"count": 0}
        for extractor in extractors:
            if extractor.is_my_job(file_path):
                result = extractor.extract("\n".join(text_json["content"]))
                for key in count_key_list:
                    result_value = result[key]
                    if (type(result_value) == int or type(result_value) == float):
                        if key in count_dict[file_path]:
                            count_dict[file_path][key] = count_dict[file_path][key] + result_value
                        else:
                            count_dict[file_path][key] = result_value
                    else:
                        if key in count_dict[file_path]:
                            if result_value in count_dict[file_path][key]:
                                count_dict[file_path][key][result_value] = count_dict[file_path][key][result_value] + 1
                            else:
                                count_dict[file_path][key][result_value] = 1
                        else:
                            count_dict[file_path][key] = {}
                            count_dict[file_path][key][result_value] = 1
        count_dict[file_path]["count"] = count_dict[file_path]["count"] + 1
        file_path, text = data_util.next_line()
    for key in count_dict:
        print(key)
        count = count_dict[key]["count"]
        for ckey in count_key_list:
            ckey_result = count_dict[key][ckey]
            if (type(ckey_result) == int or type(ckey_result) == float):
                print(str(ckey) + ":%f" % (ckey_result / float(count)))
            else:
                for cckey in ckey_result:
                    print(str(ckey) + "_" + str(cckey) + ":%f" % (ckey_result[cckey] / float(count)))
    print(count_dict)

